﻿using System.Collections.Generic;
using System.Web.Http;
using HCQ2_Common.Constant;
using HCQ2_Model.ViewModel;
using HCQ2_Model.WebApiModel.ParamModel;
using HCQ2_Model.ViewModel.WebAPI;
using HCQ2WebAPI_Logic.Model;
using System;
using System.Linq;
using HCQ2_Model;
using HCQ2_Common.Encrypt;
using HCQ2_Model.APPModel;
using HCQ2_Model.WeiXinApiModel.Model;
using HCQ2_Common;
using HCQ2_Common.Attributes;
using HCQ2_Model.VR.Model;
using HCQ2_Common.Validate;
using HCQ2_Model.SMS;
using HCQ2_Common.DD;
using HCQ2_Model.Log;
using HCQ2_Model.VRDD.OutputDto._0427;
using HCQ2_Model.VR;
using HCQ2_Model.VRDD.InputDto._0427;
using HCQ2_Model.VRDD.InputDto._0730;
using System.Web;
using WebApiThrottle;
using HCQ2WebAPI_Logic.Filters;

namespace HCQ2WebAPI_Logic.BaseAPIController
{
    /// <summary>
    ///  Web Api登录控制器
    /// </summary>
    [SkipApi]
    public class SysLoginApiController : BaseWeiXinApiLogic
    {
        /// <summary>
        ///  获取用户id通过userid
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<int?> GetIdByUserid(BaseDDAPI model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid);
            if (user_id <= 0)
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception, "userid信息异常，未找到对应user_id！", null);
            return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Ok, "成功获取用户id~", user_id);
        }
        /// <summary>
        ///  VR客户端登录 只返回userid
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<OutLoginResult> BbsUserLogin(VRLoginModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<OutLoginResult>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            OutLoginResult result = new OutLoginResult();
            LoginUser user = new LoginUser { UserPwd = model.user_password };
            LoginResultModel rModel = new LoginResultModel();
            #region 判断是度度圈时允许登录、手机号登录
            if (model.pro_type.ToLower().Equals("vcircle"))
            {
                var _u = operateContext.bllSession.T_User.Select(s => s.login_name.Equals(model.user_name) || s.user_phone.Equals(model.user_name));
                if (_u == null || _u.Count <= 0)
                    return ApiResultJsonModel<OutLoginResult>.RedirectWebApi(WebResultCode.Exception, "登录名或手机号错误！", null);
                foreach (var m in _u)
                {
                    user.LoginName = m.login_name;
                    rModel = operateContext.Login(user, model.login_source, model.pro_type, false, model.langCode);
                    if (rModel.Status)
                        break;
                }
            }
            #endregion

            #region 其他正常登录
            else
            {
                user.LoginName = model.user_name;
                rModel = operateContext.Login(user, model.login_source, model.pro_type, false, model.langCode);
            }
            #endregion            
            //1.0 判断是否登录成功
            if (!rModel.Status)
                return ApiResultJsonModel<OutLoginResult>.RedirectWebApi(WebResultCode.Exception, (!string.IsNullOrEmpty(rModel.Message)) ? rModel.Message : rModel.Msg.ToString(), null);
            //2.0 判断是否拥有文档审核权限
            result.userid = rModel.user.user_guid;
            result.id = rModel.user.user_id;
            if (operateContext.bllSession.T_DocumentInfo.IsApproveLimit(rModel.user.user_id))
                result.assessor = true;
            T_ItemCodeMenum item = operateContext.bllSession.T_ItemCodeMenum.Select(s => s.code_value.Equals(rModel.user.user_unit)).FirstOrDefault();
            if (item != null && !string.IsNullOrEmpty(item.code_name))
                result.unitname = item.code_name;
            //头像地址
            if (!string.IsNullOrEmpty(rModel.user.user_img))
            {
                if (rModel.user.user_img.IndexOf("http") < 0)
                    result.headurl = request.Url.AbsoluteUri.Substring(0, request.Url.AbsoluteUri.IndexOf("/api/")) + rModel.user.user_img.Replace("~", "");
                else
                    result.headurl = rModel.user.user_img;
            }
            //用户使用类别
            result.use_type = rModel.user.use_type;
            //收集需要验证的权限
            List<LoginLimitModel> limitList = operateContext.bllSession.T_Permissions.GetLimitList(rModel.user.user_id);
            result.limit = limitList;
            //获取用户拥有角色
            result.haveRole = operateContext.bllSession.T_Role.getUserRole(rModel.user.user_id);
            result.user_name = rModel.user.user_name;
            result.login_name = rModel.user.login_name;
            #region 判断登录用户产品类别
            if (model.pro_type.ToLower().Equals("vcircle"))
            {
                #region 判断用户是否保存了都都圈个人信息
                int dd = operateContext.bllSession.DD_User.SelectCount(s => s.du_id == rModel.user.user_id);
                if (dd <= 0)
                    operateContext.bllSession.DD_User.Add(new DD_User
                    {
                        du_id = rModel.user.user_id,
                        du_city_id = 0,
                        du_hometown_id = 0,
                        du_sex = 0,
                        count_fan = 0,
                        count_friend = 0,
                        count_visited = 0,
                        count_visitor = 0,
                        dd_verify = true,
                        dd_hidden = false,
                        hide_name = 2,
                        hide_sex = 2,
                        hide_mobile = 2,
                        hide_birthday = 2,
                        hide_city = 2,
                        hide_hometown = 2,
                        created_time = DateTime.Now
                    });
                #endregion
                #region 更新网易云信IM token值
                if (string.IsNullOrEmpty(rModel.user.user_phone))
                    return ApiResultJsonModel<OutLoginResult>.RedirectWebApi(WebResultCode.Exception, "用户手机号异常，不能更新网易云信token", null);
                string token = Helper.GetGuid;
                string imresult = IMUtil.ExecuteRequest(2, "accid=" + rModel.user.user_phone + "&token=" + token);
                IMResult json = JsonHelper.JsonStrToObject<IMResult>(imresult);
                if (json.code != 200)
                {
                    //注册网易云信
                    if (!string.IsNullOrEmpty(rModel.user.user_phone))
                    {
                        var js = IMUtil.ExecuteRequest(1, "accid=" + rModel.user.user_phone + "&name=" + rModel.user.user_name + "&token=" + token);
                        IMUtilResult t = JsonHelper.JsonStrToObject<IMUtilResult>(js);
                        if (t.code == 200)
                            result.token = token;
                    }
                }
                else
                    result.token = token;
                #endregion
            }
            #endregion
            return ApiResultJsonModel<OutLoginResult>.RedirectWebApi(WebResultCode.Ok, LangHelper.GetValue("LoginPage.LoginOk", model.langCode), result);
        }

        /// <summary>
        ///  元宇宙登录接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ModelValid]
        public WebApiResultJsonModel<UserLoginResult> UserLogin(UseLoginModel model)
        {
            var u = operateContext.bllSession.T_User.Select(s => s.login_name.Equals(model.userName) || s.user_phone.Equals(model.userName));
            if (u == null || u.Count <= 0)
                return ApiResultJsonModel<UserLoginResult>.RedirectWebApi(WebResultCode.Exception, "登录名或手机号错误！", null);
            if (u.Count > 1)
                return ApiResultJsonModel<UserLoginResult>.RedirectWebApi(WebResultCode.Exception, "登录名或手机号查询的用户超过一条！", null);
            LoginUser user = new LoginUser { LoginName = u[0].login_name, UserPwd = model.userPwd };
            LoginResultModel rModel = operateContext.Login(user, model.loginSource, model.proType, false, model.langCode);
            //1.0 判断是否登录成功
            if (!rModel.Status)
                return ApiResultJsonModel<UserLoginResult>.RedirectWebApi(WebResultCode.Exception, (!string.IsNullOrEmpty(rModel.Message)) ? rModel.Message : rModel.Msg.ToString(), null);
            //判断是否是VCircle、VMeta
            if (model.proType.ToLower().Equals("vcircle") || model.proType.ToLower().Equals("vmeta"))
            {
                #region 判断用户是否保存了都都圈个人信息
                int dd = operateContext.bllSession.DD_User.SelectCount(s => s.du_id == rModel.user.user_id);
                if (dd <= 0)
                    operateContext.bllSession.DD_User.Add(new DD_User
                    {
                        du_id = rModel.user.user_id,
                        du_city_id = 0,
                        du_hometown_id = 0,
                        du_sex = 0,
                        count_fan = 0,
                        count_friend = 0,
                        count_visited = 0,
                        count_visitor = 0,
                        dd_verify = true,
                        dd_hidden = false,
                        hide_name = 2,
                        hide_sex = 2,
                        hide_mobile = 2,
                        hide_birthday = 2,
                        hide_city = 2,
                        hide_hometown = 2,
                        created_time = DateTime.Now
                    });
                #endregion
            }
            UserLoginResult result = new UserLoginResult
            {
                id = rModel.user.user_id,
                userid = rModel.user.user_guid,
                userName = rModel.user.user_name,
                loginName = rModel.user.login_name,
                userPhone = rModel.user.user_phone,
                userSex = rModel.user.user_sex,
                userNote = rModel.user.user_note,
                unitName = rModel.user.user_unit
            };
            //头像地址
            if (!string.IsNullOrEmpty(rModel.user.user_img))
            {
                if (rModel.user.user_img.IndexOf("http") < 0)
                    result.userImage = request.Url.AbsoluteUri.Substring(0, request.Url.AbsoluteUri.IndexOf("/api/")) + rModel.user.user_img.Replace("~", "");
                else
                    result.userImage = rModel.user.user_img;
            }
            return ApiResultJsonModel<UserLoginResult>.RedirectWebApi(WebResultCode.Ok, LangHelper.GetValue("LoginPage.LoginOk", model.langCode), result);
        }

        #region 获取设备的最新扫码登录信息 + WebApiResultJsonModel<OutLoginResult> GetScanLoginByLatest(InputLatestLogin param)
        /// <summary>
        ///  获取设备的最新扫码登录信息
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<OutLoginResult> GetScanLoginByLatest(InputLatestLogin param)
        {
            //1.0 验证数据有效性
            if (!ModelState.IsValid)
                return ApiResultJsonModel<OutLoginResult>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            var login = operateContext.bllSession.T_VRDDScanLogin.FindSingle(s => s.device_id.Equals(param.device_id) && s.user_status);
            if (login == null)
                return ApiResultJsonModel<OutLoginResult>.RedirectWebApi(WebResultCode.Exception, "当前设备无扫码登录记录！", null);
            var user = operateContext.bllSession.T_User.FindSingle(s => s.user_id == login.user_id);
            if (user == null)
                return ApiResultJsonModel<OutLoginResult>.RedirectWebApi(WebResultCode.Exception, "扫码用户后台已删除或不存在！", null);
            OutLoginResult result = new OutLoginResult();
            //2.0 判断是否拥有文档审核权限
            result.userid = user.user_guid;
            result.id = user.user_id;
            if (operateContext.bllSession.T_DocumentInfo.IsApproveLimit(user.user_id))
                result.assessor = true;
            T_ItemCodeMenum item = operateContext.bllSession.T_ItemCodeMenum.Select(s => s.code_value.Equals(user.user_unit)).FirstOrDefault();
            if (item != null && !string.IsNullOrEmpty(item.code_name))
                result.unitname = item.code_name;
            //头像地址
            if (!string.IsNullOrEmpty(user.user_img))
            {
                if (user.user_img.IndexOf("http") < 0)
                    result.headurl = request.Url.AbsoluteUri.Substring(0, request.Url.AbsoluteUri.IndexOf("/api/")) + user.user_img.Replace("~", "");
                else
                    result.headurl = user.user_img;
            }
            //用户使用类别
            result.use_type = user.use_type;
            //收集需要验证的权限
            List<LoginLimitModel> limitList = operateContext.bllSession.T_Permissions.GetLimitList(user.user_id);
            result.limit = limitList;
            //获取用户拥有角色
            result.haveRole = operateContext.bllSession.T_Role.getUserRole(user.user_id);
            result.user_name = user.user_name;
            result.login_name = user.login_name;
            return ApiResultJsonModel<OutLoginResult>.RedirectWebApi(WebResultCode.Ok, "", result);
        }
        #endregion

        /// <summary>
        ///  更新用户登录状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public WebApiResultJsonModel UpdateUserLogin(InputModifyUserStatus model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            var user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(model.userid));
            if (user == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户信息异常！", null);
            if (model.type == user.user_status)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "用户状态修改成功~", "");
            //return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, $"当前用户已经出于{(model.type > 0 ? "在线" : "离线")}状态无需重复操作！", null);
            //修改用户在线状态
            operateContext.bllSession.T_User.Modify(new T_User { user_status = model.type }, s => s.user_id == user.user_id, "user_status");
            //获取用户最后一次登录日志log_code
            string loginCode = operateContext.bllSession.T_Login.GetLoginLogCode(user.user_id);
            if (string.IsNullOrEmpty(loginCode))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "修改用户状态必须先登录！", null);
            if (model.type > 0)
            {
                //最后一次登录记录
                var log = operateContext.bllSession.T_LoginLog.FindSingle(s => s.log_code.Equals(loginCode));
                //修改登录主表登录时间
                operateContext.bllSession.T_Login.Modify(new T_Login { login_time = DateTime.Now }, s => s.user_id == user.user_id, "login_time");
                //写入登录日志详情表
                operateContext.bllSession.T_LoginLog.Add(new T_LoginLog { log_code = Helper.GetGuid, user_id = user.user_id, source = log.source, login_ip = log.login_ip, login_date = DateTime.Now, pro_type = log.pro_type });
            }
            else
            {
                //离线写入登录日志表，离线时间                
                operateContext.bllSession.T_LoginLog.Modify(new T_LoginLog { out_date = DateTime.Now }, s => s.log_code.Equals(loginCode), "out_date");
            }
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "用户状态修改成功~", "");
        }

        /// <summary>
        ///  VR客户端注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel BbsRegister(VRRegisterUserModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "参数验证失败", null);
            //判断登录名是否被占用
            int count = operateContext.bllSession.T_User.SelectCount(s => s.login_name.Equals(model.loginName, StringComparison.CurrentCultureIgnoreCase));
            if (count > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前登录名已被占用~", null);
            //构建对象
            T_User user = new T_User
            {
                user_name = model.userName,
                login_name = model.loginName,
                user_pwd = EncryptHelper.Md5Encryption(model.passWord),
                user_phone = model.cellPhone,
                user_email = model.email,
                user_sex = model.userSex,
                user_guid = EncryptHelper.CreateGuidValue(),
                reg_from = 0,
                status = 1,
                max_machine = 0,
                batch_user = false,
                create_date = DateTime.Now,
                update_date = DateTime.Now
            };
            int mark = operateContext.bllSession.T_User.Add(user);
            //删除注册已发送的手机验证码
            operateContext.bllSession.T_VRCellSMSCode.Delete(s => s.phone.Equals(model.cellPhone) && s.cellType == 0);
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "注册成功~", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "注册失败~", null);
        }

        /// <summary>
        ///  APP注册【度度圈】
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <remarks>
        /// 20220623 度度圈需求 3.7 优化
        /// </remarks>
        [HttpPost]
        public WebApiResultJsonModel<OutDDRegister> ddRegister(DDRegisterUserModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<OutDDRegister>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            //判断登录名是否被占用
            int count = operateContext.bllSession.T_User.SelectCount(s => s.login_name.Equals(model.loginName, StringComparison.CurrentCultureIgnoreCase));
            if (count > 0)
                return ApiResultJsonModel<OutDDRegister>.RedirectWebApi(WebResultCode.Exception, "当前登录名已被占用，请重新设置~", null);
            //判断验证码是否正确
            var auth = operateContext.bllSession.T_VRCellSMSCode.FindSingle(s => s.phone.Equals(model.user_phone) && s.code.Equals(model.auth_code));
            if (auth == null)
                return ApiResultJsonModel<OutDDRegister>.RedirectWebApi(WebResultCode.Exception, "验证码异常或错误，请重新发送验证码~", null);
            //构建对象
            T_User user = new T_User
            {
                user_name = model.userName,
                login_name = model.loginName,
                user_pwd = EncryptHelper.Md5Encryption(model.passWord),
                user_phone = model.user_phone,
                user_sex = "男",
                user_guid = EncryptHelper.CreateGuidValue(),
                reg_from = 0,
                status = 1,
                max_machine = 0,
                batch_user = false,
                create_date = DateTime.Now,
                update_date = DateTime.Now
            };
            int mark = operateContext.bllSession.T_User.Add(user);
            IMUtilResult json = new IMUtilResult();
            string token = Helper.GetGuid;
            if (mark > 0)
            {
                #region 1.0 将用户信息写入度度圈用户表
                operateContext.bllSession.DD_User.Add(new DD_User
                {
                    du_id = user.user_id,
                    du_city_id = 0,
                    du_hometown_id = 0,
                    du_sex = 0,
                    count_fan = 0,
                    count_friend = 0,
                    count_visited = 0,
                    count_visitor = 0,
                    dd_verify = true,
                    dd_hidden = false,
                    hide_name = 2,
                    hide_sex = 2,
                    hide_mobile = 2,
                    hide_birthday = 2,
                    hide_city = 2,
                    hide_hometown = 2,
                    created_time = DateTime.Now
                });
                #endregion
                //2.0 判断是否已注册手机号，通过更新token判断是否注册过               
                string imresult = IMUtil.ExecuteRequest(2, "accid=" + model.user_phone + "&token=" + token);
                IMResult json1 = JsonHelper.JsonStrToObject<IMResult>(imresult);
                if (json1.code != 200)
                {
                    //未注册过：注册网易云信IM账号
                    imresult = IMUtil.ExecuteRequest(1, "accid=" + model.user_phone + "&name=" + model.userName + "&token=" + token);
                    json = JsonHelper.JsonStrToObject<IMUtilResult>(imresult);
                    if (json.code != 200)
                    {
                        operateContext.bllSession.T_User.Delete(s => s.user_id == user.user_id);
                        operateContext.bllSession.DD_User.Delete(s => s.du_id == user.user_id);
                        operateContext.bllSession.T_VRCellSMSCode.Delete(s => s.phone.Equals(model.user_phone));
                        return ApiResultJsonModel<OutDDRegister>.RedirectWebApi(WebResultCode.Error, $"网易云信账号注册失败，网易云信返回错误代码【{json.code}】", null);
                    }
                }
            }
            //删除已发送的手机验证码
            operateContext.bllSession.T_VRCellSMSCode.Delete(s => s.phone.Equals(model.user_phone));
            if (mark > 0)
            {
                OutDDRegister dd = new OutDDRegister
                {
                    userid = user.user_guid,
                    id = user.user_id,
                    accid = user.user_phone,
                    name = model.userName,
                    token = token
                };
                int score = 1;//默认奖励1分
                //添加数据到积分来源明细表和积分来源汇总表
                var ssmInfo1 = operateContext.bllSession.T_VRScoreSourceMain.FindSingle(o => o.user_id == user.user_id && o.itemType.Equals("Registration")  && o.proType.Equals("VCircle"));
                if (ssmInfo1 == null)
                {
                    ssmInfo1 = new T_VRScoreSourceMain
                    {
                        userid = user.user_guid,
                        user_id = user.user_id,
                        user_name = user.user_name,
                        itemType = "Registration",
                        proType = "VCircle",
                        inScore = 0,
                        outScore = 0,
                        totalScore = 0,
                        createDate = DateTime.Now,
                        updateDate = DateTime.Now,
                        logCode=Helper.GetGuid
                    };
                    operateContext.bllSession.T_VRScoreSourceMain.Add(ssmInfo1);
                }
                operateContext.bllSession.T_VRScoreSourceDetail.Add(new T_VRScoreSourceDetail {
                    userid = user.user_guid,
                    user_id = user.user_id,
                    user_name = user.user_name,
                    itemType = "Registration",
                    inScore = score,
                    outScore = 0,
                    totalScore = score,
                    proType = "VCircle",
                    createDate = DateTime.Now,
                    scoreNote = "用户注册"
                });
                operateContext.bllSession.T_VRScoreSourceMain.Modify(new T_VRScoreSourceMain { inScore =  score, totalScore = score, updateDate = DateTime.Now }, o => o.logCode.Equals(ssmInfo1.logCode), "inScore", "totalScore", "updateDate");
                //添加数据到积分来源明细表和积分来源汇总表
                var ssmInfoVMete1 = operateContext.bllSession.T_VRScoreSourceMain.FindSingle(o => o.user_id == user.user_id && o.itemType.Equals("Registration") && o.proType.Equals("VMeta"));
                if (ssmInfoVMete1 == null)
                {
                    ssmInfoVMete1 = new T_VRScoreSourceMain
                    {
                        userid = user.user_guid,
                        user_id = user.user_id,
                        user_name = user.user_name,
                        itemType = "Registration",
                        proType = "VMeta",
                        inScore = 0,
                        outScore = 0,
                        totalScore = 0,
                        createDate = DateTime.Now,
                        updateDate = DateTime.Now,
                        logCode = Helper.GetGuid
                    };
                    operateContext.bllSession.T_VRScoreSourceMain.Add(ssmInfoVMete1);
                }
                operateContext.bllSession.T_VRScoreSourceDetail.Add(new T_VRScoreSourceDetail {
                    userid = user.user_guid,
                    user_id = user.user_id,
                    user_name = user.user_name,
                    itemType = "Registration",
                    inScore = score,
                    outScore = 0,
                    totalScore = score,
                    proType = "VMeta",
                    createDate = DateTime.Now,
                    scoreNote = "用户注册"
                });
                operateContext.bllSession.T_VRScoreSourceMain.Modify(new T_VRScoreSourceMain { inScore = score, totalScore = score, updateDate = DateTime.Now }, o => o.logCode.Equals(ssmInfoVMete1.logCode), "inScore", "totalScore", "updateDate");
                return ApiResultJsonModel<OutDDRegister>.RedirectWebApi(WebResultCode.Ok, "注册成功~", dd);
            }
            return ApiResultJsonModel<OutDDRegister>.RedirectWebApi(WebResultCode.Error, "注册失败~", null);
        }

        /// <summary>
        ///  VR忘记密码，修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //[HttpPost]
        //public WebApiResultJsonModel VRModifyPassword(ModifyPasswod model)
        //{
        //    if (!ModelState.IsValid)
        //        return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "参数验证失败", null);
        //    //判断登录名是否被占用
        //    int mark = operateContext.bllSession.T_User.Modify(new T_User { user_pwd = EncryptHelper.Md5Encryption(model.passWord) }, s => s.login_name.Equals(model.loginName), "user_pwd");
        //    if (mark > 0)
        //        return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "密码修改成功~", "");
        //    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "密码修改失败~", null);
        //}

        /// <summary>
        ///  VR修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel VRChartModifyPassword(ModifyPasswodModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            //验证登录名、密码是否正确
            LoginUser user = new LoginUser()
            { LoginName = model.loginName, UserPwd = model.oldPassWord };
            LoginResultModel rModel = operateContext.Login(user, "mobile", "VLions", false);
            if (!rModel.Status)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "登录名或者原始密码错误~", null);
            int mark = operateContext.bllSession.T_User.Modify(new T_User { user_pwd = EncryptHelper.Md5Encryption(model.newPassWord) }, s => s.login_name.Equals(model.loginName), "user_pwd");
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "密码修改成功~", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "密码修改失败~", null);
        }
        /// <summary>
        /// 修改密码 【APP度度圈】
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel CircleModifyPassword(DDModifyPasswodModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if (model.user_id <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "请输入被修改用户id~", null);
            var u = operateContext.bllSession.T_User.FindSingle(s => s.user_id == model.user_id);
            if (u == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户信息后端已删除或不存在请再次确认~", null);
            string oldPass = EncryptHelper.Md5Encryption(model.oldPassWord);
            if (!oldPass.Equals(u.user_pwd))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "原始密码错误~", null);
            int mark = operateContext.bllSession.T_User.Modify(new T_User { user_pwd = EncryptHelper.Md5Encryption(model.newPassWord) }, s => s.user_id == model.user_id, "user_pwd");
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "密码修改成功~", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "密码修改失败~", null);
        }

        /// <summary>
        ///  VR头记 微信端用户注册
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        /// <remarks>
        ///  1、禅道需求：id=262 【2022-02-10】<br/>
        /// </remarks>
        [HttpPost]
        public WebApiResultJsonModel VRHeadRegister(ChartRegisterModel param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            string errmsg = string.Empty;
            //1.0 获取正式openid
            ChartUser model = GetWebChartInfo(param, out errmsg);
            if (!string.IsNullOrEmpty(errmsg))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.chartCode, "微信端接口异常信息：" + errmsg, null);
            //2.0 检测openid是否已经注册
            int mark = operateContext.bllSession.T_VRUserChartRegister.SelectCount(s => s.openid.Equals(model.openid));
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前微信用户已经注册过！", null);
            if (string.IsNullOrEmpty(param.LoginName))
                param.LoginName = Helper.GetNextGuid;
            if (string.IsNullOrEmpty(param.PWD))
                param.PWD = Helper.GetNextGuid;
            //3.0 验证登录名是否存在
            mark = operateContext.bllSession.T_User.SelectCount(s => s.login_name.Equals(param.LoginName));
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前登录名称已被注册过！", null);
            //3.0 正式注册
            T_User user = new T_User
            {
                user_name = (string.IsNullOrEmpty(param.UserName)) ? param.LoginName : param.UserName,
                login_name = param.LoginName,
                user_pwd = EncryptHelper.Md5Encryption(param.PWD),
                user_img = param.UserImage,//头像地址
                user_phone = param.UserPhone,//手机号码
                user_sex = "男",
                user_guid = Helper.GetGuid,
                status = 1,
                max_machine = 0,
                create_date = DateTime.Now,
                update_date = DateTime.Now,
                openid = model.openid
            };
            if (param.refUserId > 0)
            {
                var refUser = operateContext.bllSession.T_User.FindSingle(s => s.user_id == param.refUserId);
                if (refUser != null)
                {
                    user.ref_id = refUser.user_id;
                    user.ref_name = refUser.user_name;
                }
            }
            mark = operateContext.bllSession.T_User.Add(user);
            if (mark > 0)
            {
                operateContext.bllSession.T_VRUserChartRegister.Add(new T_VRUserChartRegister { user_id = user.user_id, openid = model.openid, reg_date = DateTime.Now });
                Dictionary<string, string> map = new Dictionary<string, string>();
                map.Add("openid", model.openid);
                map.Add("userid", user.user_guid);
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "注册并登录成功！", map);
            }
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "注册失败！", null);
        }
        /// <summary>
        ///  VR头记 微信端用户登录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel VRHeadLogin(ChartCode param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            string errmsg = string.Empty;
            //1.0 获取微信正式openid
            ChartUser model = GetWebChartInfo(param, out errmsg);
            if (!string.IsNullOrEmpty(errmsg))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.chartCode, "微信端接口异常信息：" + errmsg, null);
            //2.0 登录匹配
            var chart = operateContext.bllSession.T_VRUserChartRegister.FindSingle(s => s.openid.Equals(model.openid));
            if (chart == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前微信号未注册！", null);
            T_User user = operateContext.bllSession.T_User.FindSingle(s => s.user_id.Equals(chart.user_id));
            if (user == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前微信号关联用户已被删除或不存在！", null);
            bool ifLogin = operateContext.bllSession.T_DocEmpower.GetPowerCountByUser(user.user_id);
            if (!ifLogin)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, HCQ2UI_Helper.Session.SysPermissSession.GetPowerMessage, null);
            //3.0 写入登录日志
            var query = operateContext.bllSession.T_Login.FindSingle(s => s.user_id == user.user_id);
            if (query != null)
            {
                query.login_count += 1;
                query.last_ip = query.login_ip;
                query.last_time = DateTime.Now;
                query.login_ip = RequestHelper.GetIP;
                query.login_time = DateTime.Now;
                query.note = "";
                query.if_false = true;
                query.source = "wechat";
                operateContext.bllSession.T_Login.Modify(query, s => s.id == query.id, "login_count", "last_ip", "last_time", "login_ip", "login_time", "note", "if_false", "source");
            }
            //4.0 写入登录历史
            operateContext.bllSession.T_LoginLog.Add(new T_LoginLog
            {
                log_code = Helper.GetGuid,
                user_id = user.user_id,
                source = "wechat",
                login_ip = RequestHelper.GetIP,
                login_date = DateTime.Now
            });
            //5.0 判断是否需要重新计算用户等级
            int mark = operateContext.bllSession.T_VRUserLevelLog.CheckCountScore(user.user_id);
            if (mark > 0)
            {
                //1.0 获取需要重新计算的商铺
                var folder = operateContext.bllSession.T_VRFounderApply.Select(s => s.user_id == user.user_id && s.apply_status == 1);
                if (folder != null && folder.Count > 0)
                {
                    folder.ForEach(o =>
                    {
                        UserLevelColumn level = operateContext.bllSession.T_VRUserLevel.ResetUserLevel(user.user_id, o.folder_id, DateTime.Now.Year - 1);
                        if (level.userLevel > o.user_level)
                        {
                            //1.0 更新等级
                            operateContext.bllSession.T_VRFounderApply.Modify(new T_VRFounderApply { user_level = level.userLevel }, n => n.id == o.id, "user_level");
                            //2.0 添加等级变动日志
                            operateContext.bllSession.T_VRUserLevelLog.Add(new T_VRUserLevelLog { user_id = user.user_id, folder_id = o.folder_id, user_name = user.user_name, user_level = level.userLevel, sell_money = level.saleNum, line_num = level.lineNum, create_id = user.user_id, create_name = user.user_name, create_date = DateTime.Now });
                        }
                    });
                }
            }
            Dictionary<string, object> map = new Dictionary<string, object>();
            map.Add("openid", chart.openid);
            map.Add("userid", user.user_guid);
            map.Add("id", user.user_id);
            bool assessor = false;
            if (operateContext.bllSession.T_DocumentInfo.IsApproveLimit(user.user_id))
                assessor = true;
            map.Add("assessor", assessor);//是否拥有审核权限
            map.Add("unitname", user.user_unit);//单位名称
            string headurl = user.user_img;
            if (!string.IsNullOrEmpty(headurl) && headurl.IndexOf("http") < 0)
                headurl = headurl.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
            map.Add("headurl", headurl);//头像地址
            map.Add("use_type", user.user_type);//用户使用类别
            //收集需要验证的权限
            List<LoginLimitModel> limitList = operateContext.bllSession.T_Permissions.GetLimitList(user.user_id);
            map.Add("limit", limitList);//拥有权限
            //获取用户拥有角色
            var haveRole = operateContext.bllSession.T_Role.getUserRole(user.user_id);
            map.Add("haveRole", haveRole);//拥有角色 
            string token = string.Empty;
            //手机号不位空时
            if (!string.IsNullOrEmpty(user.user_phone))
            {
                string acctoken = Helper.GetGuid;
                string imresult = IMUtil.ExecuteRequest(2, "accid=" + user.user_phone + "&token=" + acctoken);
                IMResult json = JsonHelper.JsonStrToObject<IMResult>(imresult);
                if (json.code != 200)
                {
                    //注册网易云信
                    if (!string.IsNullOrEmpty(user.user_phone))
                    {
                        var js = IMUtil.ExecuteRequest(1, "accid=" + user.user_phone + "&name=" + user.user_name + "&token=" + acctoken);
                        IMUtilResult t = JsonHelper.JsonStrToObject<IMUtilResult>(js);
                        if (t.code == 200)
                            token = acctoken;
                    }
                }
                else
                    token = acctoken;
            }
            map.Add("token", token);//网易云信token
            map.Add("user_name", user.user_name);
            map.Add("login_name", user.login_name);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "登录成功！", map);
        }
        /// <summary>
        ///  VR头记 微信绑定
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel VRHeadBound(ChartBound param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            string errmsg = string.Empty;
            //1.0 获取微信正式openid
            ChartUser model = GetWebChartInfo(param, out errmsg);
            if (!string.IsNullOrEmpty(errmsg))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.chartCode, "微信端接口获取openid异常信息：" + errmsg, null);
            //2.0 判断微信号是否绑定过
            int mark = operateContext.bllSession.T_VRUserChartRegister.SelectCount(s => s.openid.Equals(model.openid));
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前微信号已被绑定，不允许重复绑定！：", null);
            //3.0 绑定信息
            T_User user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(param.userid));
            if (user == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "传递的用户信息异常！", null);
            operateContext.bllSession.T_VRUserChartRegister.Add(new T_VRUserChartRegister { user_id = user.user_id, openid = model.openid, reg_date = DateTime.Now });
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "绑定成功！", "");
            ////4.0 获取用户信息
            //WebChartUser chartUser = GetChartUserInfo(model, out errmsg);
            //if (!string.IsNullOrEmpty(errmsg))
            //    return ApiResultJsonModel.RedirectWebApi(WebResultCode.chartCode, "微信绑定失败，获取用户信息时异常：" + errmsg, null);
            //return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "微信绑定成功！", chartUser);
        }
        /// <summary>
        ///  VR头记 微信解绑
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel VRHeadUnBound(UserModel param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if (string.IsNullOrEmpty(param.appid))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "appid必传项！", null);
            T_User user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(param.userid));
            if (user == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户信息异常！", null);
            var chart = operateContext.bllSession.T_VRUserChartRegister.FindSingle(s => s.user_id.Equals(user.user_id) && s.openid.Equals(param.appid));
            if (chart == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前用户对应appid尚未绑定！", null);
            int mark = operateContext.bllSession.T_VRUserChartRegister.Delete(s => s.id == chart.id);
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功解除绑定！", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "成功解除失败！", "");
        }
        /// <summary>
        ///  VR头记 获取绑定微信用户的信息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel VRGetChartInfo(ChartCode param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            string errmsg = string.Empty;
            //1.0 获取微信正式openid
            ChartUser model = GetWebChartInfo(param, out errmsg);
            if (!string.IsNullOrEmpty(errmsg))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.chartCode, "微信端接口获取openid异常信息：" + errmsg, null);
            //2.0 绑定信息
            var chart = operateContext.bllSession.T_VRUserChartRegister.FindSingle(s => s.openid.Equals(model.openid));
            if (chart == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "尚未绑定！", null);
            T_User user = operateContext.bllSession.T_User.FindSingle(s => s.user_id.Equals(chart.user_id));
            if (user == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前微信号尚未绑定！", "");
            Dictionary<string, string> map = new Dictionary<string, string>();
            map.Add("userid", user.user_guid);
            map.Add("user_name", user.user_name);
            map.Add("login_name", user.login_name);
            map.Add("telPhone", user.user_phone);
            //3.0 获取用户信息
            //WebChartUser chartUser = GetChartUserInfo(model, out errmsg);
            //if (!string.IsNullOrEmpty(errmsg))
            //    map.Add("telPhone", "");
            //else
            //    map.Add("telPhone", chartUser.purePhoneNumber);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "登录成功！", map);
        }
        /// <summary>
        ///  VR头记 微信重置密码
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel VRHeadResetPwd(ChartPWD param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            string errmsg = string.Empty;
            //1.0 获取微信正式openid
            ChartUser model = GetWebChartInfo(param, out errmsg);
            if (!string.IsNullOrEmpty(errmsg))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.chartCode, "微信端接口获取openid异常信息：" + errmsg, null);
            //2.0 验证微信用户是否绑定
            var obj = operateContext.bllSession.T_VRUserChartRegister.FindSingle(s => s.openid.Equals(model.openid));
            if (obj == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前微信号尚未注册！", "");
            //3.0 判断登录名是否被占用
            int mark = operateContext.bllSession.T_User.SelectCount(s => s.login_name.Equals(param.login_name) && s.user_id != obj.user_id);
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前登录名已被占用！", "");
            //3.0 更新信息
            operateContext.bllSession.T_User.Modify(new T_User { login_name = param.login_name, user_pwd = EncryptHelper.Md5Encryption(param.pass_word) }, s => s.openid.Equals(model.openid), "login_name", "user_pwd");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "登录名、密码重置成功！", "");
        }

        /// <summary>
        ///  VR云编辑登录服务【微信】
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [LogNotParameter]
        public WebApiResultJsonModel BbsXRLogin(SysXRloginModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_User user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(model.token));
            if (user == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "唯一标记异常，请输入正确的唯一标记！", null);
            bool ifLogin = operateContext.bllSession.T_DocEmpower.GetPowerCountByUser(user.user_id);
            if (!ifLogin)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, HCQ2UI_Helper.Session.SysPermissSession.GetPowerMessage, null);
            //2.0 判断是否拥有文档审核权限
            Dictionary<string, object> map = new Dictionary<string, object>();
            map.Add("userid", user.user_guid);
            if (operateContext.bllSession.T_DocumentInfo.IsApproveLimit(user.user_id))
                map.Add("assessor", true);
            else
                map.Add("assessor", false);
            T_ItemCodeMenum item = operateContext.bllSession.T_ItemCodeMenum.Select(s => s.code_value.Equals(user.user_unit)).FirstOrDefault();
            if (item != null && !string.IsNullOrEmpty(item.code_name))
                map.Add("unitname", item.code_name);
            else
                map.Add("unitname", "");
            //头像地址
            if (!string.IsNullOrEmpty(user.user_img))
            {
                if (user.user_img.IndexOf("http") < 0)
                    map.Add("headurl", request.Url.AbsoluteUri.Substring(0, request.Url.AbsoluteUri.IndexOf("/api/")) + user.user_img.Replace("~", ""));
                else
                    map.Add("headurl", user.user_img);
            }
            else
                map.Add("headurl", "");
            //3.0 写入登录日志
            var query = operateContext.bllSession.T_Login.FindSingle(s => s.user_id == user.user_id);
            if (query != null)
            {
                query.login_count += 1;
                query.last_ip = query.login_ip;
                query.last_time = DateTime.Now;
                query.login_ip = RequestHelper.GetIP;
                query.login_time = DateTime.Now;
                query.note = "";
                query.if_false = true;
                query.source = "web";
                operateContext.bllSession.T_Login.Modify(query, s => s.id == query.id, "login_count", "last_ip", "last_time", "login_ip", "login_time", "note", "if_false", "source");
            }
            //4.0 写入登录历史
            operateContext.bllSession.T_LoginLog.Add(new T_LoginLog
            {
                log_code = Helper.GetGuid,
                user_id = user.user_id,
                source = "web",
                login_ip = RequestHelper.GetIP,
                login_date = DateTime.Now
            });
            //收集需要验证的权限
            List<LoginLimitModel> limitList = operateContext.bllSession.T_Permissions.GetLimitList(user.user_id);
            map.Add("limit", limitList);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "登录成功~", map);
        }

        //**************************************APP手机注册获取短信验证*********************************************
        #region 3.0 + WebApiResultJsonModel GetCellSMSNumber(CellSMSParam param)
        /// <summary>
        /// APP手机注册、修改密码获取短信验证【度度圈、元宇宙】
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetCellSMSNumber(CellSMSParam param)
        {
            //1.0 参数验证
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            //string userid = "14488", account = "GZLT", password = "GZLT0104";
            //发送请求contentType
            string contentType = "application/x-www-form-urlencoded";
            //发送请求超时时间
            int timeout = 8000;
            //请求接口地址
            string apiUrl = AppConfigAppSetting.GetName("MessSendUrl");
            //发送请求结果
            string sendResult = string.Empty;
            //注册
            if (param.type == 0)
            {
                //1.1 判断当前手机是否已注册
                int userCount = operateContext.bllSession.T_User.SelectCount(s => s.user_phone.Equals(param.phone));
                if (userCount > 0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, $"当前手机号【{param.phone}】已注册！", null);
            }
            //1.2 查看未获取的状态  T_VRCellSMSCode
            CellSMSStatus obj = new CellSMSStatus();
            bool exec = true;//是否继续执行
            string message = "";//返回消息
            QuerySmsData queryData = new QuerySmsData();
            TextSmsSign textSmsSign = new TextSmsSign();
            queryData.timestamp = textSmsSign.timestamp;
            queryData.sign = textSmsSign.sign;
            string queryUrl = "http://sms.izjun.cn/v2statusApi.aspx";//获取状态地址
            string queryResult = RequestHelper.SendPost(queryUrl, timeout, queryData.ToString(), contentType);
            //object json = ZjunApi.ZjunNewSMSNHandler.Instance.Report(userid, account, password);
            if (!string.IsNullOrEmpty(queryResult))
                obj = JsonHelper.JsonStrToObject<CellSMSStatus>(queryResult.ToString());
            #region 1.3  判断是否需要获取验证码
            if (obj != null && obj.Task.Count > 0)
            {
                obj.Task.ForEach(s =>
                {
                    //当前手机号
                    if (param.phone.Equals(s.Mobile))
                    {
                        var str = operateContext.bllSession.T_VRCellSMSCode.FindSingle(l => l.phone.Equals(param.phone) && l.cellType == param.type);
                        if (s.Status.Equals("10") && str?.past_date >= DateTime.Now)
                        {
                            exec = false;
                            message = "请在60秒后重新获取验证码！";
                        }
                    }
                    //更新状态
                    operateContext.bllSession.T_VRCellSMSCode.Modify(new T_VRCellSMSCode { status = s.Status }, n => n.phone.Equals(s.Mobile) && n.cellType == param.type, "status");
                });
            }
            else
            {
                //无状态返回时判断数据库中的记录
                var u = operateContext.bllSession.T_VRCellSMSCode.FindSingle(s => s.phone.Equals(param.phone) && s.cellType == param.type);
                if (u != null && u.status.Equals("10") && u.past_date >= DateTime.Now)
                {
                    exec = false;
                    message = "请在60秒后重新获取验证码！";
                }
            }
            #endregion

            #region 1.4 发送验证码
            if (string.IsNullOrEmpty(param.appName))
            {
                var item = operateContext.bllSession.T_ItemCode.FindSingle(s => s.item_code.Equals("loginProType"));
                if (null != item)
                    param.appName = operateContext.bllSession.T_ItemCodeMenum.FindSingle(s => s.item_id == item.item_id && s.code_value.Equals(param.proType))?.code_value;
            }
            if (exec)
            {
                //发送验证码
                string code = GetStrCode();//验证码
                SendSmsData sendSmsData = new SendSmsData();
                sendSmsData.timestamp = textSmsSign.timestamp;
                sendSmsData.sign = textSmsSign.sign;
                sendSmsData.mobile = param.phone;
                sendSmsData.content = $"【{param.appName}】您的注册验证码为：{code}";
                sendResult = RequestHelper.SendPost(apiUrl, timeout, sendSmsData.ToString(), contentType);
                SendResultStateParent resultStateParent = new SendResultStateParent();
                if (!string.IsNullOrEmpty(sendResult))
                    resultStateParent = JsonHelper.JsonStrToObject<SendResultStateParent>(sendResult);
                //ZjunApi.ZjunNewSMSNHandler.Instance.SendSMS(userid, account, password, param.phone, "", null, null);
                if (!resultStateParent.isSuccess().Equals("10"))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, resultStateParent.Message, null);
                var u = operateContext.bllSession.T_VRCellSMSCode.FindSingle(s => s.phone.Equals(param.phone) && s.cellType == param.type);
                T_VRCellSMSCode o = new T_VRCellSMSCode
                {
                    cell_code = Helper.GetGuid,
                    phone = param.phone,
                    code = code,
                    task_id = resultStateParent.TaskID,
                    status = resultStateParent.isSuccess(),
                    cellType = param.type,
                    past_date = DateTime.Now.AddSeconds(60)
                };
                if (u == null)
                    operateContext.bllSession.T_VRCellSMSCode.Add(o);
                else
                    operateContext.bllSession.T_VRCellSMSCode.Modify(o, s => s.phone.Equals(param.phone), "code", "past_date");
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "", "");
            }
            else
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, message, null);
            #endregion
        }
        #endregion

        #region 3.1 用短信验证码重置密码 + ResetPasswordWithSMSCode(ResetPasswordParam model)
        /// <summary>
        ///  3.1 用短信验证码重置密码
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel ResetPasswordWithSMSCode(ResetPasswordParam param)
        {
            //1.0 参数验证
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            //2.0 查找手机号对应用户
            int task = operateContext.bllSession.T_User.SelectCount(s => s.user_phone.Equals(param.phone));
            if(task<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, $"当前手机号【{param.phone}】尚未注册不能修改密码！", null);
            if(task>1)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, $"使用当前手机号【{param.phone}】账户后台有{task}人 无法确认修改某人！", null);
            //2.1 获取手机验证码
            task = operateContext.bllSession.T_VRCellSMSCode.SelectCount(s => s.phone.Equals(param.phone) && s.code.Equals(param.code) && s.cellType == 1);
            if(task<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "手机号或验证码有误！", null);
            operateContext.bllSession.T_User.Modify(new T_User { user_pwd = EncryptHelper.Md5Encryption(param.pwd) }, s => s.user_phone.Equals(param.phone), "user_pwd");
            //删除修改密码已发送的手机验证码
            operateContext.bllSession.T_VRCellSMSCode.Delete(s => s.phone.Equals(param.phone) && s.cellType == 1);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok,"密码修改成功！", null);
        }
        #endregion

        /// <summary>
        ///  生成验证码
        /// </summary>
        /// <returns></returns>
        private string GetStrCode()
        {
            //生成验证码
            ValidateCode validateCode = new ValidateCode();
            return validateCode.CreateValidateCode(4);
        }

        /// <summary>
        ///  登录服务
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //[HttpPost]
        //public object AppUserLogin(SysLoginModel model)
        //{
        //    if (!ModelState.IsValid)
        //        return OperateContext.Current.RedirectWebApi(
        //            WebResultCode.Exception, "参数验证失败", null);
        //    return Login(model);
        //}

        /// <summary>
        ///  微信用户登录接口
        /// </summary>
        /// <param name="model">参数模型</param>
        /// <returns></returns>
        //[HttpPost]
        //public object WeiXinUserLogin(SysLoginModel model)
        //{
        //    if (!ModelState.IsValid)
        //        return OperateContext.Current.RedirectWebApi(
        //                WebResultCode.Exception, "参数验证失败", null);
        //    return Login(model);
        //}

        /// <summary>
        ///  APP登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //[HttpPost]
        //public object AppUserAPILogin(SysLoginModel model)
        //{
        //    if (!ModelState.IsValid)
        //        return OperateContext.Current.RedirectWebApi(
        //                WebResultCode.Exception, "参数验证失败", null);
        //    LoginUser user = new LoginUser()
        //    { LoginName = model.user_name, UserPwd = model.user_password };
        //    LoginResultModel rModel = operateContext.Login(user, false);
        //    if (rModel.Status)
        //    {
        //        LoginAPPResultModel reg = new LoginAPPResultModel { userid = rModel.user.user_guid, user_type = rModel.user.user_type };
        //        return OperateContext.Current.RedirectWebApi(WebResultCode.Ok, "登录成功", reg);
        //    }
        //    return OperateContext.Current.RedirectWebApi(WebResultCode.Exception, (!string.IsNullOrEmpty(rModel.Message)) ? rModel.Message : rModel.Msg.ToString(), null);
        //}

        /// <summary>
        ///  公共登录方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //private object Login(SysLoginModel model)
        //{
        //    LoginUser user = new LoginUser()
        //    { LoginName = model.user_name, UserPwd = model.user_password };
        //    LoginResultModel rModel = operateContext.Login(user, false);
        //    if (rModel.Status)
        //    {
        //        List<HCQ2_Model.T_Org_User> org =
        //            operateContext.bllSession.T_Org_User.Select(s => s.user_id == rModel.user.user_id);
        //        BaseModel rUser;
        //        if (null != org && org.Count > 0)
        //            rUser = new BaseModel() { userid = rModel.user.user_guid, orgid = org?[0].UnitID };
        //        else
        //            rUser = new BaseModel() { userid = rModel.user.user_guid };
        //        return OperateContext.Current.RedirectWebApi(WebResultCode.Ok, "登录成功", rUser);
        //    }
        //    return OperateContext.Current.RedirectWebApi(WebResultCode.Exception, (!string.IsNullOrEmpty(rModel.Message)) ? rModel.Message : rModel.Msg.ToString(), null);
        //}
    }
}
